package com.lswms.modules.lswms.service.impl.receipt;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.groovy.runtime.typehandling.BigDecimalMath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lswms.common.page.PageData;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.modules.lswms.MEGConstant;
import com.lswms.modules.lswms.Constant.InventoryConstant;
import com.lswms.modules.lswms.Constant.LocationConstant;
import com.lswms.modules.lswms.Constant.ReceiptConstant;
import com.lswms.modules.lswms.Constant.TaskConstant;
import com.lswms.modules.lswms.Constant.TradeConstant;
import com.lswms.modules.lswms.dao.base.LocationDao;
import com.lswms.modules.lswms.dao.base.PutawaystrategydetailDao;
import com.lswms.modules.lswms.dao.base.SkuDao;
import com.lswms.modules.lswms.dao.base.SkucategoryDao;
import com.lswms.modules.lswms.dao.receipt.ReceiptDao;
import com.lswms.modules.lswms.dao.receipt.ReceiptdetailDao;
import com.lswms.modules.lswms.dao.receipt.ReceiptdetaillistDao;
import com.lswms.modules.lswms.dao.stock.InventoryDao;
import com.lswms.modules.lswms.dao.stock.LotDao;
import com.lswms.modules.lswms.dao.stock.TradeDao;
import com.lswms.modules.lswms.dao.task.TaskDao;
import com.lswms.modules.lswms.dao.uniquecode.UniquecodeDao;
import com.lswms.modules.lswms.dao.uniquecode.UniquecoderecordDao;
import com.lswms.modules.lswms.dto.receipt.ReceiptdetaillistDTO;
import com.lswms.modules.lswms.entity.base.LocationEntity;
import com.lswms.modules.lswms.entity.base.PutawaystrategydetailEntity;
import com.lswms.modules.lswms.entity.base.SkuEntity;
import com.lswms.modules.lswms.entity.base.SkucategoryEntity;
import com.lswms.modules.lswms.entity.receipt.ReceiptEntity;
import com.lswms.modules.lswms.entity.receipt.ReceiptdetailEntity;
import com.lswms.modules.lswms.entity.receipt.ReceiptdetaillistEntity;
import com.lswms.modules.lswms.entity.stock.InventoryEntity;
import com.lswms.modules.lswms.entity.stock.LotEntity;
import com.lswms.modules.lswms.entity.stock.TradeEntity;
import com.lswms.modules.lswms.entity.task.TaskEntity;
import com.lswms.modules.lswms.entity.uniquecode.UniquecodeEntity;
import com.lswms.modules.lswms.entity.uniquecode.UniquecoderecordEntity;
import com.lswms.modules.lswms.service.base.LocationService;
import com.lswms.modules.lswms.service.base.SequenceService;
import com.lswms.modules.lswms.service.receipt.ReceiptdetaillistService;

import lombok.extern.slf4j.Slf4j;

/**
 * 收货明细记录
 *
 * @author DX sunlightcs@gmail.com
 * @since 1.0.0 2021-06-13
 */
@Slf4j
@Service
public class ReceiptdetaillistServiceImpl
		extends CrudServiceImpl<ReceiptdetaillistDao, ReceiptdetaillistEntity, ReceiptdetaillistDTO>
		implements ReceiptdetaillistService {
	@Autowired
	LocationService locationService;

	@Autowired
	LocationDao locationDao;

	@Autowired
	InventoryDao inventoryDao;

	@Autowired
	LotDao lotDao;

	@Autowired
	TradeDao tradeDao;

	@Autowired
	ReceiptdetailDao receiptdetailDao;

	@Autowired
	ReceiptDao receiptDao;

	@Autowired
	SequenceService sequenceService;

	@Autowired
	PutawaystrategydetailDao putawaystrategydetailDao;

	@Autowired
	SkuDao skuDao;

	@Autowired
	TaskDao taskDao;

	@Autowired
	SkucategoryDao skucategoryDao;

	@Autowired
	private UniquecodeDao uniquecodeDao;

	@Autowired
	private UniquecoderecordDao uniquecoderecordDao;

	@Override
	public QueryWrapper<ReceiptdetaillistEntity> getWrapper(Map<String, Object> params) {
		String id = (String) params.get("id");
		String receiptkey = (String) params.get("receiptkey");
		String line = (String) params.get("line");
		String sku = (String) params.get("sku");
		String descr = (String) params.get("descr");
		String lot6 = (String)params.get("lot6");

		QueryWrapper<ReceiptdetaillistEntity> wrapper = new QueryWrapper<>();
		wrapper.eq(StringUtils.isNotBlank(id), "id", id);
		wrapper.eq(StringUtils.isNotBlank(receiptkey), "receiptkey", receiptkey);
		wrapper.eq(StringUtils.isNotBlank(line), "line", line);
		wrapper.eq(StringUtils.isNotBlank(sku), "lswms_receiptdetaillist.sku", sku);
		wrapper.like(StringUtils.isNotBlank(descr), "descr", descr);
		wrapper.eq(StringUtils.isNotBlank(lot6),"lot6",lot6);

		wrapper.orderByDesc(" receiptkey ");
		wrapper.orderByAsc(" line ");
		wrapper.orderByAsc(" linelist ");

		return wrapper;
	}

	@Override
	public PageData<ReceiptdetaillistEntity> pageBySql(Map<String, Object> params) {
		IPage<ReceiptdetaillistEntity> page = baseDao.selectPageBySql(getPage(params, null, false), getWrapper(params));
		return getPageData(page, ReceiptdetaillistEntity.class);
	}

	@Override
	public List<ReceiptdetaillistEntity> listBySql(Map<String, Object> params) {
		List<ReceiptdetaillistEntity> list = baseDao.listBySql(params);
		return list;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String receipt(ReceiptdetaillistEntity dto) {
		// 校验数据
		BigDecimal actqty1 = dto.getActqty();
		if (actqty1 == null || actqty1.compareTo(BigDecimal.ZERO) <= 0) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "数量不能为负数";
		}

		Date lot1Date = dto.getLot1();
		Date lot2Date = dto.getLot2();
		if (lot1Date != null) {
			if (lot1Date.compareTo(new Date()) > 0) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return "生产日期不能在今天日期之后";
			}

			if (lot2Date != null) {
				if (lot1Date.compareTo(lot2Date) >= 0) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return "生产日期不能与有效期相等或之后";
				}
			}
		}

		// 主表为11或15是,不允许收货
		QueryWrapper<ReceiptEntity> ReceiptWrapper = new QueryWrapper<>();
		ReceiptWrapper.eq("receiptkey", dto.getReceiptkey());
		ReceiptEntity receiptEntity = receiptDao.selectOne(ReceiptWrapper);
		if (receiptEntity == null || receiptEntity.getReceiptkey() == null) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return String.format(MEGConstant.RECEIPT_NOT_EXISTS, dto.getReceiptkey());
		} else {
			if (receiptEntity.getStatus() == ReceiptConstant.RECEIPTSTATUS_11) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return String.format(MEGConstant.RECEIPT_DONE, dto.getReceiptkey());
			}
		}
		// 校验

		// 校验目的库位
		String toloc = dto.getToloc();

		String toTray = dto.getTotray();
		if (toTray == null || toTray.trim().length() == 0) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "箱号不能为空，请填写箱号";
		}
		toTray = toTray.trim();

		String toBox = dto.getTobox();
		if (toBox == null || toBox.trim().length() == 0) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "格号不能为空，请填写格号";
		}
		toTray = toTray.trim();
		toBox = toBox.trim();

		// 使用的箱号是否在其他库位存在库存，若存在库存，则不允许收货
		QueryWrapper<InventoryEntity> inventoryQuery = new QueryWrapper<InventoryEntity>();
		inventoryQuery.eq("tray", toTray);
		inventoryQuery.ne("location", toloc);
		inventoryQuery.gt("qty", 0);

		Integer inventoryCount = inventoryDao.selectCount(inventoryQuery);
		if (inventoryCount > 0) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "箱号已在其他库位被使用,请更换箱号";
		}
		// 校验箱号是否有未完成的任务，有任务不允许使用
		QueryWrapper<TaskEntity> taskQuery = new QueryWrapper<TaskEntity>();
		// taskQuery.eq("tray", toTray);
		taskQuery.ne("status", TaskConstant.TASK_9);
		taskQuery.and(
				wrapper -> wrapper.eq("fromtray", dto.getTotray().trim()).or().eq("totray", dto.getTotray().trim()));
		Integer taskCount = taskDao.selectCount(taskQuery) ;
		if(taskCount>0) {
			
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return "箱号:"+ dto.getTotray().trim() + "已存在未完成的任务,请更换箱号";
		
		}
		
		// 获取目的库位信息
		QueryWrapper<LocationEntity> locationWrapper = new QueryWrapper<>();
		locationWrapper.eq("location", toloc);
		LocationEntity locationEntity = locationDao.selectOne(locationWrapper);
		if (locationEntity == null || locationEntity.getLocation() == null) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return String.format(MEGConstant.LOC_NOT_EXISTS, toloc);
		}

		if (locationEntity.getLocStatus().equals(LocationConstant.LOC_STATUS_DAMAGE)) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return MEGConstant.LOC_STATUS_DAMAGE_ERROR;
		}

		if (locationEntity.getLocCategory().equals("STEREO")) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "不能直接收货到立体库";
		}

		// 校验收货库位混放 0 可以混放，1 不允许混放
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("location", toloc);
		param.put("sku", dto.getSku());
		param.put("lot1", dto.getLot1());
		param.put("lot2", dto.getLot2());
		param.put("lot3", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot4", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot5", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot6", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot7", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot8", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot9", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot10", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot11", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot12", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot13", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot14", StringUtils.trimToEmpty(dto.getLot3()));
		param.put("lot15", StringUtils.trimToEmpty(dto.getLot3()));
		int ismixedCount = inventoryDao.canbeismixed(param);
		if (ismixedCount > 0) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return String.format(MEGConstant.LOC_NOT_MIXED, toloc);
		}

		// 查询是否存在相同批属性的lot记录
		// 存在：使用已有的lot号
		// 不存在：产生新的lot记录
		QueryWrapper<LotEntity> lotWrapper = new QueryWrapper<>();
		lotWrapper.eq("sku", dto.getSku());
//		lotWrapper.eq("lot3", StringUtils.trimToEmpty(dto.getLot3()));
//		lotWrapper.eq("lot4", StringUtils.trimToEmpty(dto.getLot4()));
//		lotWrapper.eq("lot5", StringUtils.trimToEmpty(dto.getLot5()));
		lotWrapper.eq("lot6", StringUtils.trimToEmpty(dto.getLot6()));
		lotWrapper.eq("lot7", StringUtils.trimToEmpty(dto.getLot7()));
//		lotWrapper.eq("lot8", StringUtils.trimToEmpty(dto.getLot8()));
		lotWrapper.eq("lot9", StringUtils.trimToEmpty(dto.getLot9()));
		lotWrapper.eq("lot10", StringUtils.trimToEmpty(dto.getLot10()));
//		lotWrapper.eq("lot11", StringUtils.trimToEmpty(dto.getLot11()));
//		lotWrapper.eq("lot12", StringUtils.trimToEmpty(dto.getLot12()));
//		lotWrapper.eq("lot13", StringUtils.trimToEmpty(dto.getLot13()));
//		lotWrapper.eq("lot14", StringUtils.trimToEmpty(dto.getLot14()));
//		lotWrapper.eq("lot15", StringUtils.trimToEmpty(dto.getLot15()));
		if (dto.getLot1() != null) {
			lotWrapper.and(wrapper -> wrapper.isNotNull("lot1").eq("lot1", dto.getLot1()));
		} else {
			lotWrapper.and(wrapper -> wrapper.isNull("lot1"));
		}
		if (dto.getLot2() != null) {
			lotWrapper.and(wrapper -> wrapper.isNotNull("lot2").eq("lot2", dto.getLot2()));
		} else {
			lotWrapper.and(wrapper -> wrapper.isNull("lot2"));
		}

		lotWrapper.orderByDesc("lot");
		List<LotEntity> LotEntityList = lotDao.selectList(lotWrapper);
		if (LotEntityList.size() > 0) {
			dto.setLot(LotEntityList.get(0).getLot());
		} else {
			LotEntity addLotEntity = new LotEntity();
			String lotNew = sequenceService.getSequence("lot");

			dto.setLot(lotNew);

			addLotEntity.setLot(lotNew);
			addLotEntity.setSku(dto.getSku());
			addLotEntity.setLot1(dto.getLot1());
			addLotEntity.setLot2(dto.getLot2());
			addLotEntity.setLot3(StringUtils.trimToEmpty(dto.getLot3()));
			addLotEntity.setLot4(StringUtils.trimToEmpty(dto.getLot4()));
			addLotEntity.setLot5(StringUtils.trimToEmpty(dto.getLot5()));
			addLotEntity.setLot6(StringUtils.trimToEmpty(dto.getLot6()));
			addLotEntity.setLot7(StringUtils.trimToEmpty(dto.getLot7()));
			addLotEntity.setLot8(StringUtils.trimToEmpty(dto.getLot8()));
			addLotEntity.setLot9(StringUtils.trimToEmpty(dto.getLot9()));
			addLotEntity.setLot10(StringUtils.trimToEmpty(dto.getLot10()));
			addLotEntity.setLot11(StringUtils.trimToEmpty(dto.getLot11()));
			addLotEntity.setLot12(StringUtils.trimToEmpty(dto.getLot12()));
			addLotEntity.setLot13(StringUtils.trimToEmpty(dto.getLot13()));
			addLotEntity.setLot14(StringUtils.trimToEmpty(dto.getLot14()));
			addLotEntity.setLot15(StringUtils.trimToEmpty(dto.getLot15()));
			lotDao.insert(addLotEntity);
		}

		// 相同的tray和box只存放同属性的品
//		QueryWrapper<InventoryEntity> inventoryTrayAndBoxWrapper = new QueryWrapper<>();
//		inventoryTrayAndBoxWrapper.eq("tray", toTray);
//		inventoryTrayAndBoxWrapper.eq("box", toBox);
//		inventoryTrayAndBoxWrapper.gt("qty", 0);
//		inventoryTrayAndBoxWrapper.ne("sku", dto.getSku());
//		int inventoryTrayAndBoxCount = inventoryDao.selectCount(inventoryTrayAndBoxWrapper);
//		if (inventoryTrayAndBoxCount > 0) {
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//			return String.format(MEGConstant.TRAY_BOX_NOT_MIXED, toTray, toBox);
//		}

		// 设置行数
		Integer listMaxInt = baseDao.getReceiptdetaillistMaxLine(dto.getReceiptkey(), dto.getLine());
		dto.setLinelist(listMaxInt + 1); // 增加收货明细记录
		dto.setTotray(toTray);
		dto.setTobox(toBox);
		dto.setLot3(StringUtils.trimToEmpty(dto.getLot3()));
		dto.setLot4(StringUtils.trimToEmpty(dto.getLot4()));
		dto.setLot5(StringUtils.trimToEmpty(dto.getLot5()));
		dto.setLot6(StringUtils.trimToEmpty(dto.getLot6()));
		dto.setLot7(StringUtils.trimToEmpty(dto.getLot7()));
		dto.setLot8(StringUtils.trimToEmpty(dto.getLot8()));
		dto.setLot9(StringUtils.trimToEmpty(dto.getLot9()));
		dto.setLot10(StringUtils.trimToEmpty(dto.getLot10()));
		dto.setLot11(StringUtils.trimToEmpty(dto.getLot11()));
		dto.setLot12(StringUtils.trimToEmpty(dto.getLot12()));
		dto.setLot13(StringUtils.trimToEmpty(dto.getLot13()));
		dto.setLot14(StringUtils.trimToEmpty(dto.getLot14()));
		dto.setLot15(StringUtils.trimToEmpty(dto.getLot15()));
		dto.setStatus(ReceiptConstant.RECEIPTSTATUS_9);
		dto.setId(null);
		baseDao.insert(dto);

		//查询物料信息
		QueryWrapper<SkuEntity> querySku = new QueryWrapper<SkuEntity>();
		querySku.eq("sku", dto.getSku());
		SkuEntity skuEntity = skuDao.selectOne(querySku) ;
		String isuniquecode = skuEntity.getIsuniquecode();
		// 效验数据
		if (StringUtils.isNotBlank(isuniquecode) && isuniquecode.equals("1")) {
			String uniquecodeBuild = dto.getUniquecode();
			String[] uniquecodeBuilds = uniquecodeBuild.split("\n");

			List<String> uniquecodes = new LinkedList<>();
			for (String uniquecode : uniquecodeBuilds) {
				uniquecodes.add(uniquecode);
			}
			long count = uniquecodes.stream().distinct().count();
			if (uniquecodes.size() != count) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return "请不要输入重复唯一码";
			}
			BigDecimal actqty = dto.getActqty();
			Number number = BigDecimalMath.abs(actqty);

			int i = number.intValue();
			if (i != uniquecodes.size()) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return "唯一码的数量不等于实际收货数量";
			}
			for (String uniquecode : uniquecodes) {
				if (uniquecodeDao.checkUniquecode(uniquecode) > 0) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return "此唯一码已存在:" + uniquecode;

				}
			}

			for (String uniquecode : uniquecodes) {
				// 增加唯一码记录
				UniquecodeEntity uniquecodeEntity = new UniquecodeEntity();
				uniquecodeEntity.setSku(dto.getSku());
				uniquecodeEntity.setReceiptkey(dto.getReceiptkey());
				uniquecodeEntity.setReceipttime(new Date());
				uniquecodeEntity.setTray(dto.getTotray());
				uniquecodeEntity.setBox(dto.getTobox());
				uniquecodeEntity.setLot(dto.getLot());
				uniquecodeEntity.setUniquecode(uniquecode);
				uniquecodeDao.insert(uniquecodeEntity);

				// 增加唯一码历史记录
				UniquecoderecordEntity uniquecoderecordEntity = new UniquecoderecordEntity();
				uniquecoderecordEntity.setUniquecode(uniquecode);
				uniquecoderecordEntity.setFromtray(StringUtils.EMPTY);
				uniquecoderecordEntity.setFrombox(StringUtils.EMPTY);
				uniquecoderecordEntity.setTotray(dto.getTotray());
				uniquecoderecordEntity.setTobox(dto.getTobox());
				uniquecoderecordEntity.setSku(dto.getSku());
				uniquecoderecordEntity.setLot(dto.getLot());
				uniquecoderecordEntity.setSourcetype(TradeConstant.TRADETYPE_PA);
				uniquecoderecordEntity.setSourcetable("receiptdetaillist");
				uniquecoderecordEntity.setSourceid(dto.getId());
				uniquecoderecordEntity.setSourcekey(dto.getReceiptkey());
				uniquecoderecordEntity.setSourceline(dto.getLine());
				uniquecoderecordEntity.setSourcelinelist(dto.getLinelist());
				uniquecoderecordDao.insert(uniquecoderecordEntity);
			}
		}

		// 增加库存记录
		// 已存在记录:增加库存
		// 不存在记录:新增记录
		QueryWrapper<InventoryEntity> inventoryWrapper = new QueryWrapper<>();
		inventoryWrapper.eq("sku", dto.getSku());
		inventoryWrapper.eq("lot", dto.getLot());
		inventoryWrapper.eq("location", dto.getToloc());
		inventoryWrapper.eq("tray", toTray);
		inventoryWrapper.eq("box", toBox);
		inventoryWrapper.orderByDesc("updatetime");
		List<InventoryEntity> inventoryEntityList = inventoryDao.selectList(inventoryWrapper);
		if (inventoryEntityList.size() > 0) {
			// 有多条记录,只对第一条进行更新
			InventoryEntity updateInventoryEntity = new InventoryEntity();
			updateInventoryEntity = inventoryEntityList.get(0);
			updateInventoryEntity.setQty(updateInventoryEntity.getQty().add(dto.getActqty()));
			updateInventoryEntity.setRemark(dto.getRemark());
			/*
			 * if (toloc.equalsIgnoreCase("PA")) {
			 * updateInventoryEntity.setPutqty(updateInventoryEntity.getPutqty().add(dto.
			 * getActqty())); }
			 */
			inventoryDao.updateById(updateInventoryEntity);
		} else {
			InventoryEntity addInventoryEntity = new InventoryEntity();
			addInventoryEntity.setSku(dto.getSku());
			addInventoryEntity.setLot(dto.getLot());
			addInventoryEntity.setLocation(dto.getToloc());
			addInventoryEntity.setTray(dto.getTotray());
			addInventoryEntity.setBox(dto.getTobox());
			addInventoryEntity.setQty(dto.getActqty());
			addInventoryEntity.setPickqty(new BigDecimal(0));
			addInventoryEntity.setPutqty(new BigDecimal(0));
			addInventoryEntity.setStatus(0);
			addInventoryEntity.setRemark(dto.getRemark());

//                        if (toloc.equalsIgnoreCase("PA")) {
//                                addInventoryEntity.setPutqty(addInventoryEntity.getPutqty().add(dto.getActqty()));
//                        }

			// 正常状态为0, 如果库位的状态是 HOLD ,库存设置为 1
			if (locationEntity.getLocStatus().equalsIgnoreCase(LocationConstant.LOC_STATUS_OK)) {
				addInventoryEntity.setStatus(InventoryConstant.INVENTORY_STATUS_OK);
			} else {
				addInventoryEntity.setStatus(InventoryConstant.INVENTORY_STATUS_HOLD);
			}
			inventoryDao.insert(addInventoryEntity);
		}

		// 增加交易记录
		TradeEntity addTradeEntity = new TradeEntity();
		String tradekey = sequenceService.getSequence("trade");
		addTradeEntity.setTradekey(tradekey);
		addTradeEntity.setTradetype(TradeConstant.TRADETYPE_PA);
		addTradeEntity.setSku(dto.getSku());
		addTradeEntity.setQty(dto.getActqty());
		addTradeEntity.setSourcetype("");
		addTradeEntity.setSourcekey(dto.getReceiptkey());
		addTradeEntity.setSourceline(dto.getLine());
		addTradeEntity.setSourcelinelist(dto.getLinelist());
		addTradeEntity.setFromlocation("");
		addTradeEntity.setTolocation(dto.getToloc());
		addTradeEntity.setFromtray("");
		addTradeEntity.setTotray(dto.getTotray());
		addTradeEntity.setFrombox("");
		addTradeEntity.setTobox(dto.getTobox());
		addTradeEntity.setFromlot1(null);
		addTradeEntity.setFromlot2(null);
		addTradeEntity.setFromlot3("");
		addTradeEntity.setFromlot4("");
		addTradeEntity.setFromlot5("");
		addTradeEntity.setFromlot6("");
		addTradeEntity.setFromlot7("");
		addTradeEntity.setFromlot8("");
		addTradeEntity.setFromlot9("");
		addTradeEntity.setFromlot10("");
		addTradeEntity.setFromlot11("");
		addTradeEntity.setFromlot12("");
		addTradeEntity.setFromlot13("");
		addTradeEntity.setFromlot14("");
		addTradeEntity.setFromlot15("");
		addTradeEntity.setTolot1(dto.getLot1());
		addTradeEntity.setTolot2(dto.getLot2());
		addTradeEntity.setTolot3(dto.getLot3());
		addTradeEntity.setTolot4(dto.getLot4());
		addTradeEntity.setTolot5(dto.getLot5());
		addTradeEntity.setTolot6(dto.getLot6());
		addTradeEntity.setTolot7(dto.getLot7());
		addTradeEntity.setTolot8(dto.getLot8());
		addTradeEntity.setTolot9(dto.getLot9());
		addTradeEntity.setTolot10(dto.getLot10());
		addTradeEntity.setTolot11(dto.getLot11());
		addTradeEntity.setTolot12(dto.getLot12());
		addTradeEntity.setTolot13(dto.getLot13());
		addTradeEntity.setTolot14(dto.getLot14());
		addTradeEntity.setTolot15(dto.getLot15());
		addTradeEntity.setRemark(dto.getRemark());
		addTradeEntity.setFromlot(null);
		addTradeEntity.setTolot(dto.getLot());
		tradeDao.insert(addTradeEntity);

		// 主表和明细表数据跟新

		// 跟新明细的数量 和 状态
		QueryWrapper<ReceiptdetailEntity> receiptdetailWrapper = new QueryWrapper<>();
		receiptdetailWrapper.eq("receiptkey", dto.getReceiptkey());
		receiptdetailWrapper.eq("line", dto.getLine());
		List<ReceiptdetailEntity> receiptdetails = receiptdetailDao.selectList(receiptdetailWrapper);
		if (receiptdetails.size() > 0) {
			ReceiptdetailEntity receiptdetailEntity = receiptdetails.get(0);

			BigDecimal qty = receiptdetailEntity.getQty();
			BigDecimal actqty = receiptdetailEntity.getActqty();

			BigDecimal actqtyUpdate = actqty.add(dto.getActqty());

			ReceiptdetailEntity updateReceiptdetailEntity = new ReceiptdetailEntity();
			updateReceiptdetailEntity.setActqty(actqtyUpdate);

			if (qty.compareTo(actqtyUpdate) < 0) {
				updateReceiptdetailEntity.setStatus(ReceiptConstant.RECEIPTSTATUS_9);
			} else if (qty.compareTo(actqtyUpdate) > 0) {
				if (actqtyUpdate.compareTo(new BigDecimal(0)) == 0) {
					updateReceiptdetailEntity.setStatus(ReceiptConstant.RECEIPTSTATUS_0);
				} else {
					updateReceiptdetailEntity.setStatus(ReceiptConstant.RECEIPTSTATUS_5);
				}
			} else if (qty.compareTo(actqtyUpdate) == 0) {
				if (actqtyUpdate.compareTo(new BigDecimal(0)) == 0) {
					updateReceiptdetailEntity.setStatus(ReceiptConstant.RECEIPTSTATUS_0);
				} else {
					updateReceiptdetailEntity.setStatus(ReceiptConstant.RECEIPTSTATUS_9);
				}
			}
			UpdateWrapper<ReceiptdetailEntity> receiptdetailUpdateWrapper = new UpdateWrapper<>();
			receiptdetailUpdateWrapper.eq("receiptkey", dto.getReceiptkey());
			receiptdetailUpdateWrapper.eq("line", dto.getLine());
			receiptdetailDao.update(updateReceiptdetailEntity, receiptdetailUpdateWrapper);
		}

		// 更新主表状态
		// 明细记录全部为 9 主表该为 9 ,明细全部为0, 主表为0, 明细存在5,主表为5
		// 查询明细的所有状态
		QueryWrapper<ReceiptdetailEntity> receiptdetailWrapper1 = new QueryWrapper<>();
		receiptdetailWrapper1.eq("receiptkey", dto.getReceiptkey());
		receiptdetailWrapper1.select("status");
		List<ReceiptdetailEntity> receiptdetail1s = receiptdetailDao.selectList(receiptdetailWrapper1);
		boolean exists_0 = false;
		boolean exists_5 = false;
		boolean exists_9 = false;
		for (ReceiptdetailEntity receiptdetailEntity : receiptdetail1s) {
			if (receiptdetailEntity.getStatus() == ReceiptConstant.RECEIPTSTATUS_0) {
				exists_0 = true;
			} else if (receiptdetailEntity.getStatus() == ReceiptConstant.RECEIPTSTATUS_5) {
				exists_5 = true;
			} else if (receiptdetailEntity.getStatus() == ReceiptConstant.RECEIPTSTATUS_9) {
				exists_9 = true;
			}
		}

		ReceiptEntity updateReceiptEntity = new ReceiptEntity();
		if (exists_5 || (exists_0 && exists_9)) {
			updateReceiptEntity.setStatus(ReceiptConstant.RECEIPTSTATUS_5);
		} else if (exists_0 && !exists_5 && !exists_9) {
			updateReceiptEntity.setStatus(ReceiptConstant.RECEIPTSTATUS_0);
		} else if (exists_9 && !exists_5 && !exists_0) {
			updateReceiptEntity.setStatus(ReceiptConstant.RECEIPTSTATUS_9);
		}
		UpdateWrapper<ReceiptEntity> receiptUpdateWrapper = new UpdateWrapper<>();
		receiptUpdateWrapper.eq("receiptkey", dto.getReceiptkey());
		receiptDao.update(updateReceiptEntity, receiptUpdateWrapper);

		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String putaway(String receiptkey) {
		// 获取所有收货单内，且还在PA库位的库存记录

		List<InventoryEntity> InventoryEntityList = baseDao.getPutawayList(receiptkey);

		for (InventoryEntity inventoryEntity : InventoryEntityList) {
			getPutawayTask(inventoryEntity , receiptkey);
		}

		return null;
	}



	public void getPutawayTask(InventoryEntity inventoryEntity ,String receiptket) {
		// 查询商品的上架策略

		// 如果托盘已经有未完成的上架任务，不下发下发新的上架任务
		// TaskEntity
		QueryWrapper<TaskEntity> TaskQuery = new QueryWrapper<TaskEntity>();
		TaskQuery.eq("fromtray", inventoryEntity.getTray());
		TaskQuery.ne("status", TaskConstant.TASK_9);
		Integer taskCount = taskDao.selectCount(TaskQuery);
		if (taskCount > 0) {
			log.error("托盘：" + inventoryEntity.getTray() + "有未完成的任务,无法生成上架策略");
			return;
		}

		// 通过托盘号，按box查找托盘上的上面的第一个品，以第一个品的上架策略计算上架货位
		InventoryEntity inventoryEntityCurrent = new InventoryEntity();

		QueryWrapper<InventoryEntity> inventoryWrapper = new QueryWrapper<InventoryEntity>();
		inventoryWrapper.eq("tray", inventoryEntity.getTray());
		inventoryWrapper.eq("location", inventoryEntity.getLocation());
		inventoryWrapper.gt("qty", 0); // 大于0
		inventoryWrapper.orderByAsc("box");

		List<InventoryEntity> inventoryEntityList = inventoryDao.selectList(inventoryWrapper);
		if (inventoryEntityList.size() > 0) {
			inventoryEntityCurrent = inventoryEntityList.get(0);
		} else {
			log.error("托盘：" + inventoryEntity.getTray() + "上无有效数量的库存");
			return;
		}

		// 获取商品资料信息
		QueryWrapper<SkuEntity> skuQuery = new QueryWrapper<SkuEntity>();
		skuQuery.eq("sku", inventoryEntityCurrent.getSku());
		SkuEntity skuEntityCurrent = skuDao.selectOne(skuQuery);

		// 获取商品的上架策略明细
		QueryWrapper<PutawaystrategydetailEntity> putawaystrategydetailQuery = new QueryWrapper<PutawaystrategydetailEntity>();
		putawaystrategydetailQuery.eq("strategykey", skuEntityCurrent.getStrategykey());
		putawaystrategydetailQuery.orderByAsc("orderline");
		List<PutawaystrategydetailEntity> putawaystrategydetaillist = putawaystrategydetailDao
				.selectList(putawaystrategydetailQuery);

		String toloc = null;
		// 循环上架策略查找库位
		for (PutawaystrategydetailEntity putawaystrategydetailEntity : putawaystrategydetaillist) {
			toloc = getPutawayLocation(skuEntityCurrent, inventoryEntityCurrent, putawaystrategydetailEntity);
			if (StringUtils.isNotBlank(toloc)) {
				break;
			}
		}

		// 添加任务
		if (StringUtils.isNotBlank(toloc)) {

			// 查询库位属性
			QueryWrapper<LocationEntity> queryLocation = new QueryWrapper<LocationEntity>();
			queryLocation.eq("location", toloc);
			LocationEntity locationEntity = locationDao.selectOne(queryLocation);
			String isCreate = locationEntity.getIscreate();

			// 查询托盘上的所有物料明细，每一个都写入任务
			QueryWrapper<InventoryEntity> inventoryQuery = new QueryWrapper<InventoryEntity>();
			inventoryQuery.eq("location", inventoryEntityCurrent.getLocation());
			inventoryQuery.eq("tray", inventoryEntityCurrent.getTray());

			List<InventoryEntity> list = inventoryDao.selectList(inventoryQuery);

			for (InventoryEntity inventoryTask : list) {
				if (StringUtils.isNotBlank(isCreate) && isCreate.equals("1")) {
					TaskEntity taskEntity = new TaskEntity();
					String taskkey = sequenceService.getSequence("task");

					taskEntity.setTaskkey(taskkey);
					taskEntity.setTasktype(TaskConstant.TASK_PA);
					taskEntity.setPriority(0);
					taskEntity.setStatus(TaskConstant.TASK_0);
					taskEntity.setSku(inventoryTask.getSku());
					taskEntity.setQty(inventoryTask.getQty());
					taskEntity.setFromlocation(inventoryTask.getLocation());
					taskEntity.setTolocation(toloc);
					taskEntity.setFromtray(inventoryTask.getTray());
					taskEntity.setTotray(inventoryTask.getTray());
					taskEntity.setFrombox(inventoryTask.getBox());
					taskEntity.setTobox(inventoryTask.getBox());
					taskEntity.setFromlot(inventoryTask.getLot());
					taskEntity.setTolot(inventoryTask.getLot());
					taskEntity.setRemark(inventoryTask.getRemark());
					taskDao.insert(taskEntity);

					// 检查目的库位是否有已有相同的库存记录
					QueryWrapper<InventoryEntity> queryInventoryToloc = new QueryWrapper<InventoryEntity>();
					queryInventoryToloc.eq("lot", inventoryTask.getLot());
					queryInventoryToloc.eq("location", toloc);
					queryInventoryToloc.eq("sku", inventoryTask.getSku());
					queryInventoryToloc.eq("tray", inventoryTask.getTray());
					queryInventoryToloc.eq("box", inventoryTask.getBox());
					InventoryEntity inventoryToloc = inventoryDao.selectOne(queryInventoryToloc);
					if (inventoryToloc != null) {
						InventoryEntity updateInventoryEntity = new InventoryEntity();
						updateInventoryEntity.setPutqty(inventoryTask.getQty());
						UpdateWrapper<InventoryEntity> updateInventory = new UpdateWrapper<InventoryEntity>();
						updateInventory.eq("lot", inventoryTask.getLot());
						updateInventory.eq("location", toloc);
						updateInventory.eq("sku", inventoryTask.getSku());
						updateInventory.eq("tray", inventoryTask.getTray());
						updateInventory.eq("box", inventoryTask.getBox());
						inventoryDao.update(updateInventoryEntity, updateInventory);
					} else {
						InventoryEntity addInventoryEntity = new InventoryEntity();
						addInventoryEntity.setSku(inventoryTask.getSku());
						addInventoryEntity.setLot(inventoryTask.getLot());
						addInventoryEntity.setLocation(toloc);
						addInventoryEntity.setTray(inventoryTask.getTray());
						addInventoryEntity.setBox(inventoryTask.getBox());
						addInventoryEntity.setQty(new BigDecimal(0));
						addInventoryEntity.setPickqty(new BigDecimal(0));
						addInventoryEntity.setPutqty(inventoryTask.getQty());
						addInventoryEntity.setStatus(0);
						addInventoryEntity.setRemark(inventoryTask.getRemark());
						if(receiptket!=""&&receiptket!=null){
							addInventoryEntity.setReceiptkey(receiptket);
						}

						inventoryDao.insert(addInventoryEntity);
					}
				} else {
					//起始库位扣减库存
					InventoryEntity updateInventoryEntityFromloc = new InventoryEntity();
					updateInventoryEntityFromloc.setQty(  BigDecimal.ZERO);
					UpdateWrapper<InventoryEntity> updateInventoryFromloc = new UpdateWrapper<InventoryEntity>();
					updateInventoryFromloc.eq("lot", inventoryTask.getLot());
					updateInventoryFromloc.eq("location", inventoryTask.getLocation());
					updateInventoryFromloc.eq("sku", inventoryTask.getSku());
					updateInventoryFromloc.eq("tray", inventoryTask.getTray());
					updateInventoryFromloc.eq("box", inventoryTask.getBox());
					inventoryDao.update(updateInventoryEntityFromloc, updateInventoryFromloc);
					
					//目的库位增加库存 检查目的库位是否有已有相同的库存记录
					QueryWrapper<InventoryEntity> queryInventoryToloc = new QueryWrapper<InventoryEntity>();
					queryInventoryToloc.eq("lot", inventoryTask.getLot());
					queryInventoryToloc.eq("location", toloc);
					queryInventoryToloc.eq("sku", inventoryTask.getSku());
					queryInventoryToloc.eq("tray", inventoryTask.getTray());
					queryInventoryToloc.eq("box", inventoryTask.getBox());
					InventoryEntity inventoryToloc = inventoryDao.selectOne(queryInventoryToloc);
					if (inventoryToloc != null) {
						InventoryEntity updateInventoryEntity = new InventoryEntity();
						updateInventoryEntity.setQty( inventoryToloc.getQty().add(inventoryTask.getQty()));
						UpdateWrapper<InventoryEntity> updateInventory = new UpdateWrapper<InventoryEntity>();
						updateInventory.eq("lot", inventoryTask.getLot());
						updateInventory.eq("location", toloc);
						updateInventory.eq("sku", inventoryTask.getSku());
						updateInventory.eq("tray", inventoryTask.getTray());
						updateInventory.eq("box", inventoryTask.getBox());
						inventoryDao.update(updateInventoryEntity, updateInventory);
					} else {
						InventoryEntity addInventoryEntity = new InventoryEntity();
						addInventoryEntity.setSku(inventoryTask.getSku());
						addInventoryEntity.setLot(inventoryTask.getLot());
						addInventoryEntity.setLocation(toloc);
						addInventoryEntity.setTray(inventoryTask.getTray());
						addInventoryEntity.setBox(inventoryTask.getBox());
						addInventoryEntity.setQty(inventoryTask.getQty());
						addInventoryEntity.setPickqty(new BigDecimal(0));
						addInventoryEntity.setPutqty(new BigDecimal(0));
						addInventoryEntity.setStatus(0);
						addInventoryEntity.setRemark(inventoryTask.getRemark());
						inventoryDao.insert(addInventoryEntity);
					}
					
					String tradekey = sequenceService.getSequence("trade");
					TradeEntity tradeEntity = new TradeEntity();

					tradeEntity.setTradekey(tradekey);
					tradeEntity.setTradetype(TradeConstant.TRADETYPE_MV);
					tradeEntity.setSku(inventoryTask.getSku());
					tradeEntity.setQty(inventoryTask.getQty());
					tradeEntity.setSourcetype(TradeConstant.SOURCETYPE_MOVE);
					tradeEntity.setSourcekey(null);
					tradeEntity.setSourceline(null);
					tradeEntity.setSourcelinelist(null);
					tradeEntity.setFromlocation(inventoryTask.getLocation());
					tradeEntity.setTolocation(toloc);
					tradeEntity.setFromtray(inventoryTask.getTray());
					tradeEntity.setTotray(inventoryTask.getTray());
					tradeEntity.setFrombox(inventoryTask.getBox());
					tradeEntity.setTobox(inventoryTask.getBox());
					tradeEntity.setFromlot(inventoryTask.getLot());
					tradeEntity.setTolot(inventoryTask.getLot());
					tradeEntity.setFromlot1(null);
					tradeEntity.setFromlot2(null);
					tradeEntity.setFromlot3("");
					tradeEntity.setFromlot4("");
					tradeEntity.setFromlot5("");
					tradeEntity.setFromlot6("");
					tradeEntity.setFromlot7("");
					tradeEntity.setFromlot8("");
					tradeEntity.setFromlot9("");
					tradeEntity.setFromlot10("");
					tradeEntity.setFromlot11("");
					tradeEntity.setFromlot12("");
					tradeEntity.setFromlot13("");
					tradeEntity.setFromlot14("");
					tradeEntity.setFromlot15("");
					tradeEntity.setTolot1(null);
					tradeEntity.setTolot2(null);
					tradeEntity.setTolot3("");
					tradeEntity.setTolot4("");
					tradeEntity.setTolot5("");
					tradeEntity.setTolot6("");
					tradeEntity.setTolot7("");
					tradeEntity.setTolot8("");
					tradeEntity.setTolot9("");
					tradeEntity.setTolot10("");
					tradeEntity.setTolot11("");
					tradeEntity.setTolot12("");
					tradeEntity.setTolot13("");
					tradeEntity.setTolot14("");
					tradeEntity.setTolot15("");
					tradeDao.insert(tradeEntity);
				}
			}
		} else {
			log.error("箱号：" + inventoryEntity.getTray() + "没有计算到可用的上架货位，无法生成上架任务");
		}

	}

	// 执行上架策略明细
	private String getPutawayLocation(SkuEntity skuEntity, InventoryEntity inventoryEntity,
			PutawaystrategydetailEntity putawaystrategydetailEntity) {
		String strategycode = putawaystrategydetailEntity.getStrategycode();
		if (strategycode.equals("XYZ")) {
			return getPutawayLocationByXYZ(skuEntity, inventoryEntity, putawaystrategydetailEntity);
		}

		return null;
	}

	private String getPutawayLocationByXYZ(SkuEntity skuEntity, InventoryEntity inventoryEntity,
			PutawaystrategydetailEntity putawaystrategydetailEntity) {

		// 判断自库位 库存的库位与上架策略上设定的库位对比
		String fromloc = putawaystrategydetailEntity.getFromloc();
		if (StringUtils.isNotBlank(fromloc) && inventoryEntity.getLocation() != fromloc) {
			return null;
		}

		// 判断托盘类型 与库存上的托盘对比
		String trayType = putawaystrategydetailEntity.getTraytype();
		if (StringUtils.isNotBlank(trayType) && !inventoryEntity.getTray().startsWith(trayType)) {
			return null;
		}

		// 判断物料类别
		String skuSort = putawaystrategydetailEntity.getSkusort();
		if (StringUtils.isNotBlank(skuSort) && !skuEntity.getSort().equals(skuSort)) {
			// 查询所有的类别
			List<SkucategoryEntity> list = skucategoryDao.selectList(null);

			String skuEntitySort = skuEntity.getSort();

			boolean isChild = false;

			for (SkucategoryEntity skucategoryEntity : list) {
				if (skucategoryEntity.getCategorykey().equals(skuEntitySort)) {
					long pid = skucategoryEntity.getPid();
					// 查找父类是否为上架规则的类别
					isChild = isChild(skuSort, list, pid);
					if (isChild) {
						break;
					}
				}
			}
			if (!isChild) {
				return null;
			}
		}

		// 查询库存所在的区域
		QueryWrapper<LocationEntity> getInventoryLocationZoneQuery = new QueryWrapper<LocationEntity>();
		getInventoryLocationZoneQuery.eq("location", inventoryEntity.getLocation());
		LocationEntity getInventoryLocationZoneEntity = locationDao.selectOne(getInventoryLocationZoneQuery);

		// 判断自区 库存库位所对应的区
		String fromZone = putawaystrategydetailEntity.getFromzonecode();
		if (StringUtils.isNotBlank(fromZone) && getInventoryLocationZoneEntity.getZonecode() != fromZone) {
			return null;
		}

		// 库位查询条件
		QueryWrapper<LocationEntity> getPutawayLocationQuery = new QueryWrapper<LocationEntity>();

		// 设置至区
		String toZone = putawaystrategydetailEntity.getTozonecode();
		getPutawayLocationQuery.eq(StringUtils.isNotBlank(toZone), "zonecode", toZone);

		// 设置至库位
		String toloc = putawaystrategydetailEntity.getToloc();
		getPutawayLocationQuery.eq(StringUtils.isNotBlank(toloc), "location", toloc);

		// 设置库位类型
		String locType = putawaystrategydetailEntity.getLocType();
		getPutawayLocationQuery.eq(StringUtils.isNotBlank(locType), "loc_type", locType);

		// 设置库位类别
		String locCategory = putawaystrategydetailEntity.getLocCategory();
		getPutawayLocationQuery.eq(StringUtils.isNotBlank(locCategory), "loc_category", locCategory);

		// 设置库位状态
		String locStatus = putawaystrategydetailEntity.getLocStatus();
		getPutawayLocationQuery.eq(StringUtils.isNotBlank(locStatus), "loc_status", locStatus);

		// 设置巷道
		String lane = putawaystrategydetailEntity.getLane();
		getPutawayLocationQuery.eq(StringUtils.isNotBlank(lane), "lane", lane);

		// 设置巷道侧边
		String laneSide = putawaystrategydetailEntity.getLaneSide();
		getPutawayLocationQuery.eq(StringUtils.isNotBlank(laneSide), "lane_side", laneSide);

		// 设置巷道侧边深度
		Integer laneDepth = putawaystrategydetailEntity.getLaneDepth();
		getPutawayLocationQuery.eq(laneDepth != null, "lane_depth", laneDepth);

		getPutawayLocationQuery.notExists(
				"select  1 from lswms_inventory  where lswms_inventory.location = lswms_location.location and ( qty>0 or putqty>0  ) ");

		getPutawayLocationQuery.notExists(
				"select  1 from WCS_DDJ  where lswms_location.lane = WCS_DDJ.DVC_NO and WCS_DDJ.status <>'1' ");

		// 排列层排序
		String rowcollevorder = putawaystrategydetailEntity.getRowcollevorder();
		// 排顺序
		String roworder = putawaystrategydetailEntity.getRoworder();

		String columnorder = putawaystrategydetailEntity.getColumnorder();

		String levelorder = putawaystrategydetailEntity.getLevelorder();

		if (StringUtils.isBlank(rowcollevorder)) {
			getPutawayLocationQuery.orderByAsc("loc_row").orderByAsc("loc_column").orderByAsc("loc_level");
		} else {

			char[] rowcollevorderChars = rowcollevorder.toCharArray();
			// 第一层排序
			if (rowcollevorderChars[0] == 'X') {
				if (roworder.equals("tosmaller")) {
					getPutawayLocationQuery.orderByDesc("loc_row");
				} else {
					getPutawayLocationQuery.orderByAsc("loc_row");
				}
			}
			if (rowcollevorderChars[0] == 'Y') {
				if (columnorder.equals("tosmaller")) {
					getPutawayLocationQuery.orderByDesc("loc_column");
				} else {
					getPutawayLocationQuery.orderByAsc("loc_column");
				}

			}
			if (rowcollevorderChars[0] == 'Z') {
				if (levelorder.equals("tosmaller")) {
					getPutawayLocationQuery.orderByDesc("loc_level");
				} else {
					getPutawayLocationQuery.orderByAsc("loc_level");
				}
			}

			// 第二层排序
			if (rowcollevorderChars[1] == 'X') {
				if (roworder.equals("tosmaller")) {
					getPutawayLocationQuery.orderByDesc("loc_row");
				} else {
					getPutawayLocationQuery.orderByAsc("loc_row");
				}
			}
			if (rowcollevorderChars[1] == 'Y') {
				if (columnorder.equals("tosmaller")) {
					getPutawayLocationQuery.orderByDesc("loc_column");
				} else {
					getPutawayLocationQuery.orderByAsc("loc_column");
				}

			}
			if (rowcollevorderChars[1] == 'Z') {
				if (levelorder.equals("tosmaller")) {
					getPutawayLocationQuery.orderByDesc("loc_level");
				} else {
					getPutawayLocationQuery.orderByAsc("loc_level");
				}

			}

			// 第三层排序
			if (rowcollevorderChars[2] == 'X') {
				if (roworder.equals("tosmaller")) {
					getPutawayLocationQuery.orderByDesc("loc_row");
				} else {
					getPutawayLocationQuery.orderByAsc("loc_row");
				}
			}
			if (rowcollevorderChars[2] == 'Y') {
				if (columnorder.equals("tosmaller")) {
					getPutawayLocationQuery.orderByDesc("loc_column");
				} else {
					getPutawayLocationQuery.orderByAsc("loc_column");
				}
			}
			if (rowcollevorderChars[2] == 'Z') {
				if (levelorder.equals("tosmaller")) {
					getPutawayLocationQuery.orderByDesc("loc_level");
				} else {
					getPutawayLocationQuery.orderByAsc("loc_level");
				}
			}
		}

		List<LocationEntity> locations = locationDao.selectList(getPutawayLocationQuery);
		if (locations.size() > 0) {
			return locations.get(0).getLocation();
		}
		return null;
	}

	private Boolean isChild(String skuSort, List<SkucategoryEntity> list, long id) {
		for (SkucategoryEntity skucategoryEntity : list) {
			if (skucategoryEntity.getId() == id) {
				String categorykey = skucategoryEntity.getCategorykey();
				if (categorykey.equals(skuSort)) {
					return true;
				} else {
					return isChild(skuSort, list, skucategoryEntity.getPid());
				}

			}

		}
		return false;
	}

	

}
